﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HbmTools
{
    public partial class FormDbView : Form
    {
        public FormDbView()
        {
            InitializeComponent();
        }

        private void FormDbView_Load(object sender, EventArgs e)
        {

            FileInfo fileInfo = new FileInfo(Application.StartupPath + "/Data/WinHBM.sqlite");
            if(!fileInfo.Exists)
            {
                MessageBox.Show("数据库文件不存在");
                return;
            }

            if(fileInfo.Length == 0)
            {
                MessageBox.Show("数据库大小为0");
                return;
            }

            try
            {
                List<Dictionary<string, string>> tables = SQLiteHelper.Instance.ExecuteQuery("select * from sqlite_master where type='table'", null);
                for (int i = 0; i < tables.Count; i++)
                {
                    Dictionary<string, string> row = tables[i];
                    listBox1.Items.Add(row["name"]);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("打开数据库失败："+ex.Message);
            }
            
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string table = this.listBox1.SelectedItem.ToString();

            string sql = "select * from `"+table+"`";

            List<Dictionary<string, string>> rows = SQLiteHelper.Instance.ExecuteQuery(sql, null);
            DataTable dt = new DataTable();
            for (int i = 0; i < rows.Count; i++)
            {
                Dictionary<string, string> row = rows[i];
                if (i == 0)
                {
                    dataGridView1.Columns.Clear();

                    foreach (string key in row.Keys)
                    {
                        dt.Columns.Add(new DataColumn(key));
                    }

                }
                
                DataRow rw = dt.NewRow();
                foreach (string key in row.Keys)
                {
                    rw[key] = row[key].ToString();
                }
                dt.Rows.Add(rw);
            }
            dataGridView1.DataSource = dt;


        }
    }
}
